<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="600px" style="display: flex;">
        <el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"
          style="height: 600px;width: 200px;">
          <el-sub-menu index="1">
            <template #title>Explore</template>
            <el-menu-item index="1-1">Reservation</el-menu-item>
            <el-menu-item index="1-2">Search</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="2">
            <template #title>Itinerary</template>
            <el-menu-item :index="index" v-for="(item,index) in plans" @click="scrollset(index)">Day
              {{item.name}}</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="3">
            <svg width="19" height="20" viewBox="0 0 19 20" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path fill-rule="evenodd" clip-rule="evenodd"
                d="M1.66663 5C1.66663 3.61929 2.78591 2.5 4.16663 2.5H11.6666C13.0473 2.5 14.1666 3.61929 14.1666 5V5.83333H15.8333C17.214 5.83333 18.3333 6.95262 18.3333 8.33333V15C18.3333 16.3807 17.214 17.5 15.8333 17.5H4.16663C2.78591 17.5 1.66663 16.3807 1.66663 15V5ZM16.6666 12.5V10.8333H13.3333V12.5H16.6666ZM16.6666 9.16667H13.3333C12.4128 9.16667 11.6666 9.91286 11.6666 10.8333V12.5C11.6666 13.4205 12.4128 14.1667 13.3333 14.1667H16.6666V15C16.6666 15.4602 16.2935 15.8333 15.8333 15.8333H4.16663C3.70639 15.8333 3.33329 15.4602 3.33329 15V7.5H15.8333C16.2935 7.5 16.6666 7.8731 16.6666 8.33333V9.16667ZM12.5 5V5.83333H3.33329V5C3.33329 4.53976 3.70639 4.16667 4.16663 4.16667H11.6666C12.1269 4.16667 12.5 4.53976 12.5 5Z"
                fill="#777777" />
            </svg>

            <span>Budget</span>
          </el-menu-item>


        </el-menu>
        <el-scrollbar ref="scroll" height="600px">
          <ul class="infinite-list">


            <draggable v-for="(item,index)  in plans" :list="item.content" ghost-class="ghost"
              chosen-class="chosenClass" animation="300" @start="onStart" @end="onEnd">
              <template #item="{ element }">
                <div class="item">
                  <li :key="index" ref="scrollbarRef">
                    <el-card style="width: 400px;margin-bottom: 1px;">

                      <div class="card-header">
                        <span>{{ element.titlename }}</span>
                      </div>
                      <div v-if="element.bustime" style="display: flex;justify-content: space-between;">
                        <div class="time">
                          <span>{{ element.bustime }}</span>
                        </div>
                        <div>
                          <svg style="width: 14px;height: 14px;" t="1723325498674" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4423" width="200" height="200"><path d="M932.244 262.558l-19.133 0 0-95.666c0-31.57-23.103-68.956-51.335-83.067 0 0-101.731-50.866-350.465-50.866s-350.454 50.866-350.454 50.866c-28.24 14.111-51.344 51.497-51.344 83.067l0 95.666-19.133 0c-31.57 0-57.399 25.829-57.399 57.399l0 57.399c0 31.57 25.829 57.399 57.399 57.399l19.133 0 0 392.233c0 24.863 16.043 46.092 38.267 54.022l0 32.077c0 42.094 34.439 76.533 76.533 76.533s76.533-34.441 76.533-76.533l0-28.7 420.933 0 0 28.7c0 42.094 34.439 76.533 76.533 76.533s76.533-34.441 76.533-76.533l0-32.077c22.223-7.931 38.267-29.169 38.267-54.022l0-392.233 19.133 0c31.57 0 57.399-25.829 57.399-57.399l0-57.399c0-31.569-25.829-57.399-57.399-57.399zM319.978 128.625c0-10.523 8.61-19.133 19.133-19.133l344.399 0c10.523 0 19.133 8.61 19.133 19.133l0 38.267c0 10.523-8.61 19.133-19.133 19.133l-344.399 0c-10.523 0-19.133-8.61-19.133-19.133l0-38.267zM233.878 807.857c-26.423 0-47.833-21.429-47.833-47.833s21.41-47.833 47.833-47.833c26.414 0 47.833 21.429 47.833 47.833s-21.419 47.833-47.833 47.833zM788.745 807.857c-26.423 0-47.833-21.429-47.833-47.833s21.41-47.833 47.833-47.833 47.833 21.429 47.833 47.833-21.411 47.833-47.833 47.833zM836.577 587.825c0 10.523-8.61 19.133-19.133 19.133l-612.265 0c-10.523 0-19.133-8.61-19.133-19.133l0-306.133c0-10.523 8.61-19.133 19.133-19.133l612.265 0c10.523 0 19.133 8.61 19.133 19.133l0 306.133z" fill="#bfbfbf" p-id="4424"></path></svg>
                          <svg style="width: 14px;height: 14px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" ><path fill="currentColor" d="M340.864 149.312a30.592 30.592 0 0 0 0 42.752L652.736 512 340.864 831.872a30.592 30.592 0 0 0 0 42.752 29.12 29.12 0 0 0 41.728 0L714.24 534.336a32 32 0 0 0 0-44.672L382.592 149.376a29.12 29.12 0 0 0-41.728 0z"></path></svg>
                         
                        </div>
                      
                      </div>
                      <div class="item-main" @click="select(index,element)">
                        <div style="padding-right: 15px;">
                          <img class="item-main-img" :src="element.image" alt="">
                        </div>
                        <div class="item-main-content">
                          <div class="land">{{element.name}}</div>
                          <div class="land-ch">{{element.titleCh}}</div>
                          <div style="display: flex;flex-direction: row;
                        align-items: flex-end;">
                            <div class="land-ch">{{element.score}}</div>
                            <el-rate v-model="element.score" disabled size="small" />
                            <div class="land-ch">{{'('+1901+')'}}</div>
                          </div>
                          <div class="land-ch">
                            {{element.type}}
                          </div>
                          <div class="land-ch">
                            {{element.remark}}
                          </div>

                        </div>
                      </div>
                      <template #footer>
                        <div class="overview">
                          <div>Overview</div>
                          <div>{{element.overview}}</div>

                        </div>
                        <el-collapse v-model="activeNames" @change="handleChange">
                          <el-collapse-item title="Consistency" name="1">
                            <div style="display: flex;">
                              <div style="width: 100px;height: 80px;"></div>
                            </div>
                          </el-collapse-item>

                        </el-collapse>

                        <div class="selection" v-if="element.checkBox">
                          <div>
                            <el-checkbox v-model="element.selection">selection</el-checkbox>
                          </div>

                          <div style="display: flex;" @click="del(index,element)">
                            <i style="height: 50px;line-height: 50px;margin-right: 5px;color: #ff4848;"
                              class="far fa-trash-can"></i>
                            <div style="color: #ff4848;">deletion</div>
                          </div>

                        </div>
                      </template>
                    </el-card>
                  </li>
                </div>
              </template>
            </draggable>

            <li>
              <div style="height: 300px;"></div>
            </li>

          </ul>
        </el-scrollbar>
      </el-aside>
      <el-main style="display: flex;width: 430px;height: 580px;">

        <!-- <Map :GuidEntity="plans" /> -->

        <div id="container" style="position: relative; height: 100%; width: 100%"></div>
      </el-main>
    </el-container>

  </div>
</template>
<script lang="ts" setup>

  import { onMounted, onBeforeUnmount, onUnmounted } from 'vue';
  import draggable from "vuedraggable";
  import Cookies from 'js-cookie';
  import { useRoute } from 'vue-router';

  import { guid, addUserguid } from '@/api/index';
  import { ref } from 'vue'
  import { ElScrollbar } from 'element-plus'
  import { ElAmap } from "@vuemap/vue-amap";
  import AMapLoader from "@amap/amap-jsapi-loader";
  // import Map from '@/components/Map/index.vue';
  const router = useRoute();

  const item = ref("");
  const data = ref({});
  const plans = ref([]);
  const doubleClickZoom = ref(true);

  const map = ref()
  // 类型定义
  const scroll = ref < InstanceType < typeof ElScrollbar > | null > (null);
  const control = ref({
    scale: {},
    zoom: {
      position: 'bottomRight',
    },
  })


  //... ...
  onMounted(() => {
    window.onbeforeunload = function (event) {
      // alert ("===οnbefοreunlοad===");
      if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
        // alert ("你关闭了浏览器");
        setCookie()
      } else {
        // alert ("你正在刷新页面");
        setCookie()
      }
    }
    
    if (router.query.id) {
    item.value = router.query.id
    getGuid();
  }
  if(router.query.date){
    mapload()
    console.log(router.query.date)
    const Dates = getDatesBetween(router.query.date[0],router.query.date[1])
    console.log(Dates)
    for (let index = 0; index < Dates.length; index++) {
      let date =  Dates[index];
      let obj = {
        date:date,
        name:index+1,
        title:"第" + (index+1)+"天"
      }
      plans.value.push(obj)
      
    }
  }



  })


  onBeforeUnmount(() => {
    console.log('组件即将卸载');
    map.value?.destroy();
    setCookie()
    // 进行必要的清理操作，比如移除事件监听器
  });


  function del(index, params) {
    const element = plans.value[index].content
    for (let i = element.length - 1; i >= 0; i--) {
      const el = element[i];
      if (el.image === params.image) {
        element.splice(i, 1);
      }
    }
    plans.value[index].content = element

  }

  function setTitle() {

    for (let index = 0; index < plans.value.length; index++) {
      const element = plans.value[index];
      for (let i = 0; i < element.content.length; i++) {
        const el = element.content[i];

        if (i == 0) {

          el['titlename'] = "DAY " + element.name + "-" + formatDate(element.date)
        }
        // console.log(i)
        if (i > 0) {
          el['titlename'] = "Depart from " + element.content[i - 1].name
          el['bustime'] =  element.content[i - 1].endTime + " - " + element.content[i].startTime
        }
      }
    }
  }


  function select(index, params) {
    const element = plans.value[index].content
    for (let index = 0; index < element.length; index++) {
      const el = element[index];
      if (el.image == params.image) {
        if (el.checkBox) {
          el.checkBox = false
        } else {
          el['checkBox'] = true
        }
      }
    }
    plans.value[index].content = element
  }

  //拖拽开始的事件
  const onStart = () => {
    console.log("开始拖拽");
  };

  //拖拽结束的事件
  const onEnd = () => {
    console.log("结束拖拽");
    console.log(plans.value)
    setTitle();

  };

  async function setCookie() {
    // Cookies.set(plans.value.id+'-plans',JSON.stringify(plans.value))
    data.value.plans = plans.value
    // addUserGuid(data.value).then(res => {

    // })
  }


  const count = ref(0)
  const value = ref(3.7)


  const load = () => {
    count.value += 2
  }

  function mapload() {
    AMapLoader.load({
      key: "db17a89f9c977760ebb6a8ca01e092b8", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0" // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      // plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
      console.log(plans.value)
      let center = [116.397428, 39.90923];
      if (null != plans.value && plans.value.length > 0 && null != plans.value[0].content) {
        let first = plans.value[0].content[0]
        center = [first.longitude, first.latitude]
      }

      map.value = new AMap.Map("container", {
        // 设置地图容器id
        // viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: center, // 初始化地图中心点位置
      });

      if (null != plans.value && plans.value.length > 0) {
        let x = 0;
        let markers = [];
        for (let index = 0; index < plans.value.length; index++) {
          const element = plans.value[index].content;
          for (let j = 0; j < element.length; j++) {
            x = x + 1;
            const planitem = element[j];
            let markerContent = '' +
              '<div style=" position: relative;">' +
              '   <img style=" width: 25px;height: 34px;" src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">' +
              '   <div style="position: absolute;top: 5px;right: 1px;width: 15px;height: 15px;font-size: 12px;color:#fff">' + x + '</div>' +
              '</div>';
            console.log(planitem)
            if (planitem.longitude && planitem.latitude) {
              let position = new AMap.LngLat(planitem.longitude, planitem.latitude); //Marker 经纬度
              let marker = new AMap.Marker({
                position: position,
                content: markerContent, //将 html 传给 content
                offset: new AMap.Pixel(-13, -30), //以 icon 的 [center bottom] 为原点
              });
              markers.push(marker)
            }
          }
        }
        map.value.add(markers);
      }

    })
      .catch((e) => {
        console.log(e);
      });
  }

  function getGuid() {
    guid({ id: item.value }).then(res => {
      data.value = res.data
      plans.value = res.data.plans
      setTitle()
      mapload()
    })
  }


  function formatDate(string) {
    const date = new Date(string);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    const day = date.getDate();
    const month = months[date.getMonth()];
    const weekday = days[date.getDay()];

    return `${day} ${month} ${weekday}`;
  }


  function scrollset(index) {


    let l = 0;
    for (let i = 0; i < index; i++) {
      const element = plans.value[i]
      console.log(element.content.length)
      l = l + element.content.length
    }

    scroll.value.setScrollTop(l * 300)

  }




  function calculateDaysBetweenDates(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    // 计算两个日期之间的差值（以毫秒为单位）
    const diffInMillis = endDate - startDate;

    // 将毫秒转换为天数
    const diffInDays = Math.ceil(diffInMillis / (1000 * 60 * 60 * 24));

    return diffInDays;
}


function getDatesBetween(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);
    
    // 结果数组
    const dates = [];
    
    // 当前日期从起始日期开始
    let currentDate = new Date(startDate);
    
    // 循环直到当前日期超过结束日期
    while (currentDate <= endDate) {
        // 将当前日期格式化为字符串并添加到结果数组
        dates.push(new Date(currentDate).toISOString().split('T')[0]);
        
        // 将当前日期增加一天
        currentDate.setDate(currentDate.getDate() + 1);
    }
    
    return dates;
}

</script>
<style>
  .selection {
    display: flex;
    justify-content: space-evenly;
    justify-items: center;
    height: 50px;
    line-height: 50px;
    width: 100%;
  }

  .item-main {
    display: flex;
    justify-content: space-around;
    padding-top: 15px;
  }

  .infinite-list {
    width: 440px;
    height: 600px;
    padding: 0;
    margin: 0;
    list-style: none;
  }



  .item-main-img {
    margin-left: 15px;
    width: 140px;
    height: 110px;
  }

  .land {
    font-size: 14px;
  }

  .land-ch {
    font-size: 8px;
    color: #8f8f8f;
  }

  .overview {
    background-color: #ddd;
    padding: 10px;
    font-size: 9px;
    border-radius: 10px;
  }

  .el-collapse-item__content {

    padding-bottom: 0px;
  }

  .el-card {
    /* --el-card-border-color: var(--el-border-color-light); */
    --el-card-border-radius: 4px;
    --el-card-padding: 20px;
    --el-card-bg-color: var(--el-fill-color-blank);
    background-color: var(--el-card-bg-color);
    border: 1px solid var(--el-card-border-color);
    border-radius: var(--el-card-border-radius);
    color: var(--el-text-color-primary);
    overflow: hidden;
    transition: var(--el-transition-duration);
  }

  .el-card__footer {
    border-top: 0px solid var(--el-card-border-color);
    box-sizing: border-box;
    padding: 0px 10px 0px 10px;
  }

  .card-header {

    border-bottom: 0px;
  }
  .time{
    font-size: 14px;
    color: #8f8f8f;
  }
</style>